package com.cakemallproject.controller;

import com.cakemallproject.Util.JwtUtil;
import com.cakemallproject.pojo.Result;
import com.cakemallproject.pojo.mapperObj.User;
import com.cakemallproject.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.UUID;

@Slf4j
@RestController
public class AccountController {
    @Autowired
    private UsersService usersService;

    /*
     * 登录,返回token
     * */
    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        log.info("user :{}", user);
        user = usersService.login(user);
        if (user != null) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("uid", user.getUid());
            if (user.getIsAdmin()) {
                map.put("isAdmin",true);
            }
            String token = JwtUtil.getToken(map);
            return Result.success(token);
        } else {
            return Result.error("登录失败", null);
        }
    }

    /*
     *
     * 通过token获取用户信息
     * */
    @GetMapping("/login/{token}")
    public Result loginByToken(@PathVariable String token) {
        log.info("token: {}", token);
        //解析token获取uid,通过uid获取user
        Integer uid;
        try {
            uid = (Integer) JwtUtil.parseToken(token).get("uid");
        } catch (RuntimeException e) {
            return Result.error("Invalid_token");
        }
        User user = usersService.loginByUid(uid);
        //敏感信息拦截
        user.setPassword(null);
        return Result.success(user);

    }

    /*
     *
     * 注册，返回一个token
     * */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        log.info("注册 {}", user);
        try {
            usersService.insert(user);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return Result.error("username_exist");
        }
        user = usersService.getByUsername(user.getUsername());
        HashMap<String, Object> map = new HashMap<>();
        map.put("uid", user.getUid());
        String token = JwtUtil.getToken(map);
        return Result.success(token);
    }


    @Autowired
    JavaMailSender javaMailSender;

    @GetMapping("/sendMail/{email}")
    public Result sendMail(@PathVariable String email ) {
        log.info("发送验证码到：{}",email);

        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 5);
        String text = "验证码：[" + code + "]    \n" +
                "您的邮箱正在注册网上蛋糕商城,这是你的唯一验证码,有效期一分钟,请尽快使用。";

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setSubject("验证码邮件");
        simpleMailMessage.setFrom("3396915212@qq.com");
        simpleMailMessage.setTo(email);
        simpleMailMessage.setText(text);

        javaMailSender.send(simpleMailMessage);

        return Result.success(DigestUtils.md5Hex(code));
    }
}
